package com.dobby.xmlrpc.demo.metablog;

import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * maven依赖 ：
 * <dependency>
 *    <groupId>org.apache.xmlrpc</groupId>
      <artifactId>xmlrpc-client</artifactId>
 *    <version>3.1.3</version>
 *  </dependency>
 * Created by jonas on 2016/12/2.
 */
public class MetaWeblogPoster {

    private static XmlRpcClient blogClient;

    private static WebClient webClient = null;

    private MetaWeblogPoster() {
    }

    private MetaWeblogPoster(XmlRpcClient blogClient) {
        this.blogClient = blogClient;
    }


    private static WebClient getWebClient() {
        if(webClient == null) {
            webClient = new WebClient();
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setRedirectEnabled(true);
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());
            webClient.getCookieManager().setCookiesEnabled(true);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setTimeout(10000);
            webClient.waitForBackgroundJavaScript(10000);
        }
        return webClient;
    }

    public static MetaWeblogPoster init(String blogApiUrl) {
        if (null == blogApiUrl || "".equals(blogApiUrl)) {
            System.out.println("BlogApiUrl 不能为空!");
        } else {
            try {
                XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl();
                clientConfig.setServerURL(new URL(blogApiUrl));
                XmlRpcClient blogClient = new XmlRpcClient();
                blogClient.setConfig(clientConfig);
                return new MetaWeblogPoster(blogClient);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 发布博客文章
     * @param username
     * @param password
     * @param title  博客标题
     * @param content 博客内容
     * @return 成功返回 blogid，失败返回 null
     */
    public String post(String username, String password, String title, String content) {

        Map<String, Object> post = new HashMap<String, Object>();
        post.put("title", title);
        post.put("description", content);
        Object[] params = new Object[] {"_blogid", username, password, post, Boolean.TRUE};
        try {
            String result = (String) blogClient.execute("metaWeblog.newPost", params);
            System.out.println("发布新的博文, blogid= " + result);
            return result;
        } catch (XmlRpcException e) {
            e.printStackTrace();
            System.out.println("发布博文失败!");
            return null;
        }

    }


    public String edit(String postId, String username, String password, String title, String content) {

        Map<String, Object> post = new HashMap<String, Object>();
        post.put("title", title);
        post.put("description", content);
        Object[] params = new Object[] {postId, username, password, post, Boolean.TRUE};
        try {
            String result = (String) blogClient.execute("metaWeblog.editPost", params);
            System.out.println("修改博文, blogid= " + result);
            return result;
        } catch (XmlRpcException e) {
            e.printStackTrace();
            System.out.println("修改博文失败!");
            return null;
        }

    }



    public boolean delete(String postId, String username, String password) {

        Object[] params = new Object[] {"appKey", postId, username, password, Boolean.TRUE};
        try {
            Boolean result = (Boolean) blogClient.execute("blogger.deletePost", params);
            return result;
        } catch (XmlRpcException e) {
            e.printStackTrace();
            return false;
        }

    }






    /**
     *
     * @return
     */
    public String getPost(String postid, String username, String password) {
        Object[] params = new Object[] {postid, username, password};
        try {
            Object execute = blogClient.execute("metaWeblog.getPost", params);
            return null;
        } catch (XmlRpcException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取新浪博客的统计信息
     * @param postid
     * @return
     * @throws IOException
     */
    public String getPostStatInfo(String postid) throws IOException {
        String url = "http://blog.sina.com.cn/s/blog_" + postid + ".html";
        WebRequest webRequest = new WebRequest(new URL(url), HttpMethod.GET);
        WebClient client = getWebClient();
        HtmlPage resultPage = client.getPage(webRequest);

        System.out.println(resultPage.asXml());
        resultPage.asXml();

        List<HtmlDivision> byXPath = (List<HtmlDivision>) resultPage.getByXPath("//div[@id='articlebody']/div[@class='articalInfo']/div[@class='IL']");
        System.out.println(byXPath);

        HtmlSpan read = (HtmlSpan) resultPage.getElementById("r_" + postid);
        HtmlSpan comment = (HtmlSpan) resultPage.getElementById("c_" + postid);
        DomElement favorite = resultPage.getElementById("f_" + postid);
        DomElement zhuan = resultPage.getElementById("z_" + postid);
        HtmlParagraph like = (HtmlParagraph) resultPage.getElementById("dbox2_" + postid);


        Page page = client.getPage(url);
        String contentAsString = page.getWebResponse().getContentAsString();
        System.out.println(contentAsString);

        Document parse = Jsoup.parse(contentAsString);
        Element elementById = parse.getElementById("r_" + postid);
        return null;
    }





    /**
     *  判断用户是否开通博客
     * @param userName
     * @param password
     * @return
     */
    public String getUsersBlogs(String userName, String password) {
        Object[] params = new Object[] {"appKey", userName, password};
        try {
            Object execute = blogClient.execute("blogger.getUsersBlogs", params);
            if(null == execute) {
                return "未开通博客";
            } else {
                return "已开通博客";
            }
        } catch (XmlRpcException e) {
            e.printStackTrace();
            String message = e.getMessage(); //用户密码错误.  // 用户不存在.
            if(StringUtils.contains(message, "用户不存在")) {
                return "用户不存在";
            } else if(StringUtils.contains(message, "用户密码错误")) {
                return "用户密码错误";
            }
            return message;
        }
    }



    public void  getInfo() {

    }


}
